#include <QtSql/QSqlRelationalDelegate>
#include <QDebug>
#include <QTableView>
#include <QtSql/QSqlTableModel>
#include <QtSql/QSqlError>
#include <QApplication>
#include <QStringList>
#include <QLabel>
#include <QtSql/QSqlQuery>
#include "listener.h"
#include "ui_mainwindow.h"

QString dbconnect(){
	QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
	db.setDatabaseName("wpblog");
	db.setUserName("root");
	db.setPassword("liqiang");
	
	if(!db.open()){
		QStringList sl;
		sl+=db.lastError().text();
		sl+="()";
		sl+=qt_error_string();
		
		qCritical("can't open database:%s (%s)"
			,db.lastError().text().toLatin1().data(),
			qt_error_string().toLocal8Bit().data());
		return sl.join(",");
	}else{
		qDebug() <<" database opened";
		return "ok"; 
	}
}

QSqlDatabase open(){
	QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
	db.setDatabaseName("wpblog");
	db.setUserName("root");
	db.setPassword("liqiang");
	
	db.open();
	return db;
}

QStringList databases(){
	QSqlDatabase db=open();
	QSqlQuery query;
	query.exec("show databases");
	QStringList rets;
	while(query.next()){
		QString ret=query.value(0).toString();
		rets+=ret;
	}
	return rets;
}



void Listener::itemSelectionChanged ( ){
	QList<QListWidgetItem *> items=ui->listWidget->selectedItems();
	if(items.count()>0)
		ui->label->setText(items[0]->text());
		
	
}


int main(int argc,char* argv[]){
	QApplication app(argc,argv);
	
	QString str=dbconnect();
		
	QMainWindow win;
	Ui_MainWindow ui;
	ui.setupUi(&win);
	
	QStringList dbs=databases();
	QStringList::const_iterator it=dbs.begin();
	for(;it!=dbs.end();++it){
		ui.listWidget->addItem(*it);
	}
	
	Listener li(&ui);
	QObject::connect(ui.listWidget,SIGNAL(itemSelectionChanged (  )),
		&li,SLOT(itemSelectionChanged ()));

	ui.label->setText("note me");
	
	win.show();
	
	return app.exec();
}